package org.example.hansp.reflection.compare;

import org.example.hansp.reflection.demo1.Cat;
import org.junit.jupiter.api.Test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectionVSCommand {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Cat cat = new Cat();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 90000000; i++) {
            cat.test();
        }
        long end = System.currentTimeMillis();
        System.out.println("传统耗时：" + (end - start) + "ms");


        Class clazz = Class.forName("org.example.hansp.reflection.demo1.Cat");
        Object o = clazz.newInstance();
        Method test = clazz.getMethod("test");

        long start2 = System.currentTimeMillis();
        for (int i = 0; i < 90000000; i++) {
            test.invoke(o);
        }
        long end2 = System.currentTimeMillis();
        System.out.println("反射机制耗时：" + (end2 - start2) + "ms");

    }

    @Test
    public void test() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Class clazz = Class.forName("org.example.hansp.reflection.demo1.Cat");
        Object o = clazz.newInstance();
        Method test = clazz.getMethod("test");
        test.setAccessible(true);//取消访问检查，提高效率
        long start2 = System.currentTimeMillis();
        for (int i = 0; i < 90000000; i++) {
            test.invoke(o);
        }
        long end2 = System.currentTimeMillis();
        System.out.println("反射机制耗时：" + (end2 - start2) + "ms");
    }
}
